#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
from hashlib import md5

try:
    from Crypto.Cipher import AES
    from Crypto.Util.Padding import pad, unpad
except ImportError:
    print('请安装加解密库 pycryptodome')

'''
AES加密: CBC, utf-8, pkcs7
网站验证 http://tool.chacuo.net/cryptaes
'''
class AesTool(object):
    def __init__(self, key, iv):
        # self.key = '1234567812345678'.encode('utf-8')
        # self.iv = '1234567812345678'.encode('utf-8')
        self.key = key.encode('utf-8')
        self.iv = iv.encode('utf-8')
        self.mode = AES.MODE_CBC

    def encode(self, data):
        cipher = AES.new(self.key, self.mode, self.iv)
        pad_pkcs7 = pad(data.encode('utf-8'), AES.block_size, style='pkcs7')
        result = base64.encodebytes(cipher.encrypt(pad_pkcs7))
        encrypted_text = str(result, encoding='utf-8').replace('\n', '')
        return encrypted_text

    def decode(self, data):
        cipher = AES.new(self.key, self.mode, self.iv)
        base64_decrypted = base64.decodebytes(data.encode('utf-8'))
        una_pkcs7 = unpad(cipher.decrypt(base64_decrypted), AES.block_size, style='pkcs7')
        decrypted_text = str(una_pkcs7, encoding='utf-8')
        return decrypted_text

    def test(self):
        data1 = 'hello world!'
        data2 = '9DWgpIr5W1mKg/TJfxY4EA=='
        print('加密结果：', self.encode(data1))
        try:
            print('解密结果：', self.decode(data2))
        except Exception as e:
            print(e)


if __name__ == '__main__':
    aeskey = '1234567812345678'
    iv = '1234567887654321'
    blog = AesTool(aeskey, iv)
    blog.test()

    dd = b'hello world'
    print(dd)
    print(dd.decode())
    bodymd5 = md5(dd.decode().encode('utf-8')).hexdigest()
    print(bodymd5)